<?php 
/**
 * return.php
 *
 * return management
 *
 * @author     Makai Lajos
 * @copyright  2015
 * @license    License.txt
 * @version    2.0
 * @link       http://opencart-api.com/product/opencart-restful-api-pro-v2-0/
 * @see        http://newapi.opencart-api.com/demo/
 */
require_once(DIR_SYSTEM . 'engine/restcontroller.php');

class ControllerRestReturn extends RestController {

	private $error = array();

	/*
	* Get return
	*/
  	public function loadReturns() {

		$json = array('success' => true);
		$data = array();

		if (!$this->customer->isLogged()) {
			$json["success"] = false;		
			$json["error"] = "User is not logged!";		
		}
		
		if(!isset($json["error"])){
			$this->load->model('account/return');
			$this->load->language('account/return');

			$data['returns'] = array();

			$results = $this->model_account_return->getReturns(0, 1000);

			foreach ($results as $result) {
				$data['returns'][] = array(
					'return_id'  => $result['return_id'],
					'order_id'   => $result['order_id'],
					'name'       => $result['firstname'] . ' ' . $result['lastname'],
					'status'     => $result['status'],
					'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added']))
				);
			}
		}

		$json['data'] = $data;

		$this->sendResponse($json);
	}

	/* 
	* Get return info
	*/
	public function getReturnInfo($return_id) {

		if (!$this->customer->isLogged()) {
			$json["success"] = false;
			$json["error"] = "User is not logged!";
		}

		$data = array();

		if(!isset($json["error"])) {
			$this->load->language('account/return');
			$json = array('success' => true);
			$this->load->model('account/return');

			$return_info = $this->model_account_return->getReturn($return_id);

			if ($return_info) {

				$data['return_id'] = $return_info['return_id'];
				$data['order_id'] = $return_info['order_id'];
				$data['date_ordered'] = date($this->language->get('date_format_short'), strtotime($return_info['date_ordered']));
				$data['date_added'] = date($this->language->get('date_format_short'), strtotime($return_info['date_added']));
				$data['firstname'] = $return_info['firstname'];
				$data['lastname'] = $return_info['lastname'];
				$data['email'] = $return_info['email'];
				$data['telephone'] = $return_info['telephone'];
				$data['product'] = $return_info['product'];
				$data['model'] = $return_info['model'];
				$data['quantity'] = $return_info['quantity'];
				$data['reason'] = $return_info['reason'];
				$data['opened'] = $return_info['opened'] ? $this->language->get('text_yes') : $this->language->get('text_no');
				$data['comment'] = nl2br($return_info['comment']);
				$data['action'] = $return_info['action'];

				$data['histories'] = array();

				$results = $this->model_account_return->getReturnHistories($return_info['return_id']);

				foreach ($results as $result) {
					$data['histories'][] = array(
						'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
						'status'     => $result['status'],
						'comment'    => nl2br($result['comment'])
					);
				}
			}
		}
		$json['data'] = $data;

		$this->sendResponse($json);
	}

	/* 
	* Add return
	*/

	public function addReturn($request) {
        $json = array('success' => true);

        if (!$this->customer->isLogged()) {
            $json["success"] = false;
            $json["error"] = "User is not logged!";
        }

        if(!isset($json["error"])) {

            $this->load->language('account/return');

            $this->load->model('account/return');

            if ($this->validate($request)) {
                $json['data']['id'] = $this->model_account_return->addReturn($request);
            } else {
                $json['succes'] = false;
                $json['error'] = $this->error;
            }
        }

        $this->sendResponse($json);
	}

	protected function validate($post) {

		if (!$post['order_id']) {
			$this->error['order_id'] = $this->language->get('error_order_id');
		}

		if ((utf8_strlen(trim($post['firstname'])) < 1) || (utf8_strlen(trim($post['firstname'])) > 32)) {
			$this->error['firstname'] = $this->language->get('error_firstname');
		}

		if ((utf8_strlen(trim($post['lastname'])) < 1) || (utf8_strlen(trim($post['lastname'])) > 32)) {
			$this->error['lastname'] = $this->language->get('error_lastname');
		}

		if ((utf8_strlen($post['email']) > 96) || !preg_match('/^[^\@]+@.*.[a-z]{2,15}$/i', $post['email'])) {
			$this->error['email'] = $this->language->get('error_email');
		}

		if ((utf8_strlen($post['telephone']) < 3) || (utf8_strlen($post['telephone']) > 32)) {
			$this->error['telephone'] = $this->language->get('error_telephone');
		}

		if ((utf8_strlen($post['product']) < 1) || (utf8_strlen($post['product']) > 255)) {
			$this->error['product'] = $this->language->get('error_product');
		}

		if ((utf8_strlen($post['model']) < 1) || (utf8_strlen($post['model']) > 64)) {
			$this->error['model'] = $this->language->get('error_model');
		}

		if (empty($post['return_reason_id'])) {
			$this->error['reason'] = $this->language->get('error_reason');
		}

		return !$this->error;
	}
	/*
	* RETURN FUNCTIONS
	*/	
	public function returns() {

		$this->checkPlugin();

		if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
			if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])) {
				$this->getReturnInfo($this->request->get['id']);
			}else {
				$this->loadReturns();
			}
		} else if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
            $requestjson = file_get_contents('php://input');

            $requestjson = json_decode($requestjson, true);

            if (!empty($requestjson)) {
                $this->addReturn($requestjson);
            }else {
                $this->response->setOutput(json_encode(array('success' => false)));
            }

		}
    }
}